from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import numpy as np
import pyqtgraph as pg
# pg.setConfigOption('background', '#E3E6E3')
# pg.setConfigOption('foreground', 'k')
from pyqtgraph import GraphicsLayoutWidget

class GraphWidget(GraphicsLayoutWidget):
    def __init__(self):
        super(GraphWidget, self).__init__()
        # 右上角显示
        self.label = pg.LabelItem(justify='right')
        self.addItem(self.label, 0, 1, 1, 1)
        self.pg = pg
        # 曲线添加
        self.plot = self.pg.PlotItem()
        self.plot = self.addPlot(1, 1, colspan=2)
        self.plot.setYRange(0, 100)

        self.data = np.random.normal(size=10)
        self.curve_master_data = [100, 100]
        self.curve_slave_data = [0, 0]
        self.curve_data_x = [0, 300]
        # 曲线设置
        self.plot.setAutoVisible(y=True)
        self.plot.setTitle('通道数据实时曲线图')
        self.plot.setLabel('left', "相对剂量(%)", units='')
        self.plot.setLabel('bottom', "距离(mm)", units='')
        self.plot.addLegend()
        # self.plot.setRange(xRange=[0,300],yRange=[0,110],padding=0)
        # self.plot.setLimits(xMin=0,xMax=300,yMin=0,yMax=110)
        # 主测通道和监测通道
        self.curve_master = self.plot.plot(self.curve_data_x, self.curve_master_data, name='主测通道',
                                           pen=self.pg.mkPen('r', width=2))
        self.curve_slave = self.plot.plot(self.curve_data_x, self.curve_slave_data, name='监测通道',
                                          pen=self.pg.mkPen('g', width=2))
        # 网格显示
        self.plot.showGrid(x=True, y=True, alpha=0.7)
        # 鼠标坐标显示文本
        self.text_pos = self.pg.TextItem("(0,0)", anchor=(0.5, -1.0), color='r')
        self.plot.addItem(self.text_pos)
        self.text_pos.setPos(0, 0)
        # 鼠标十字移动
        self.vLine = self.pg.InfiniteLine(pen=self.pg.mkPen('b', width=1), angle=90, movable=False)
        self.hLine = self.pg.InfiniteLine(pen=self.pg.mkPen('b', width=1), angle=0, movable=False)
        self.plot.addItem(self.vLine, ignoreBounds=True)
        self.plot.addItem(self.hLine, ignoreBounds=True)
        # 鼠标移动绑定
        self.vb = self.plot.vb
        self.proxy = self.pg.SignalProxy(self.plot.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
        self.plot.autoRange()

    def find_nearest(self, array, value):
        idx = (np.abs(array - value)).argmin()
        return array[idx]

    def mouseMoved(self, evt):
        tx = np.array(self.curve_data_x)
        pos = evt[0]
        if self.plot.sceneBoundingRect().contains(pos):
            mousePoint = self.vb.mapSceneToView(pos)
            self.vLine.setPos(mousePoint.x())
            self.hLine.setPos(mousePoint.y())
            self.setCursor(Qt.BlankCursor)
            self.text_pos.setText("(%0.1f,%0.1f)" % (mousePoint.x(), mousePoint.y()))
            self.text_pos.setPos(mousePoint.x(), mousePoint.y())
            # self.label.setText("<span style='font-size: 12pt'>x=%0.1f,  <span style='color: red'>y=%0.1f</span>" % (mousePoint.x(), mousePoint.y()))
            # index = int(mousePoint.x())
            # try:
            # n = self.find_nearest(tx,index)
            # index = np.where(tx==n)[0][0]
            # self.label.setText("<span style='font-size: 12pt;color: blue'>通道实时数据:  </span>\
            # <span style='font-size: 12pt'>x=\t{:20},  \
            # <span style='color: red'>y1=\t{:28}</span> ,\
            # <span style='color: green'>y2=\t{:32}</span>"\
            # .format('%0.1f'%mousePoint.x(), '%0.1f'%self.curve_master_data[index],'%0.1f'%self.curve_slave_data[index]))
            # self.vLine.setPos(mousePoint.x())
            # self.hLine.setPos(mousePoint.y())
            # except:
            # pass

    def drawLine(self, x, y):
        self.curve_master.setData(x=self.curve_data_x, y=self.curve_master_data)
        self.curve_slave.setData(x=self.curve_data_x, y=self.curve_slave_data)

    def draw_two(self, x, master, slave):
        if master and slave:
            if max(master) == 0 or max(slave) == 0:
                master = [m * 100 / (max(master) + 0.000001) for m in master]
                slave = [m * 100 / (max(slave) + 0.000001) for m in slave]
            else:
                master = [m * 100 / max(master) for m in master]
                slave = [m * 100 / max(slave) for m in slave]
            self.curve_master.setData(x=x, y=master)
            self.curve_slave.setData(x=x, y=slave)
        else:
            self.curve_master.setData(x=[], y=[])
            self.curve_slave.setData(x=[], y=[])
        # self.plot.setXRange(0,300)
        # self.plot.setYRange(0,120)

    def clear_data(self):
        self.curve_data_x = []
        self.curve_master_data = []
        self.curve_slave_data = []
        self.curve_master.setData(x=self.curve_data_x, y=self.curve_master_data)
        self.curve_slave.setData(x=self.curve_data_x, y=self.curve_slave_data)

    def drawLineAppend(self):
        self.curve_master.setData(self.curve_master_data)
        self.curve_slave.setData(self.curve_slave_data)

    def tunnelZero(self):
        self.curve_data_x = []
        self.curve_slave_data = []
        self.curve_master_data = []
        self.drawLine()
    
    def setAxisRange(self, t):
        """曲线固定x轴范围"""
        if t['type'] == 'PDD':
            x_list = [x[2] for x in t['road']]
            self.plot.setLimits(xMin=min(x_list), xMax=max(x_list), yMin=0, yMax=110)
        if t['type'] == 'OAR':
            x_list = []
            if t['angle'] == '0' or t['angle'] == '180':
                if t['direction'] == 'G->T' or t['direction'] == 'T->G':
                    x_list = [x[1] for x in t['road']]
                else:
                    x_list = [x[0] for x in t['road']]
            if t['angle'] == '90' or t['angle'] == '270':
                if t['direction'] == 'G->T' or t['direction'] == 'T->G':
                    x_list = [x[0] for x in t['road']]
                else:
                    x_list = [x[1] for x in t['road']]
            if x_list:
                self.plot.setLimits(xMin=min(x_list) - 10, xMax=max(x_list) + 10, yMin=0, yMax=110)
            else:
                self.plot.setLimits(xMin=-200, xMax=200, yMin=0, yMax=110)
